﻿using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using HF.Framework.DataClientDBAgent;
using HF.WorkFlow.DataContract;
using HF.Framework.SqlDataContract;
using HF.User.Data;
using HF.WorkFlow.Const;
using HF.Framework.Log;
namespace HF.WorkFlow.Engine
{
    /// <summary>
    /// 数据访问类WorkTaskInstance。
    /// </summary>
    public class WorkTaskInstance
    {
        #region  私有字段
        private SqlDataItem sqlDataItem = new SqlDataItem();
        private string[] fieldList = { "WorkTaskInstanceId", "WorkFlowId", "WorkTaskId", "WorkFlowInstanceId",
                                         "PreviousTaskInstanceId", "TaskInstanceCaption", "StartTime", "EndTime",
                                         "Status", "OperatedDes", "OperatorInstanceId", "SuccessMsg", "OutTimeed",
                                         "Reminded", "Description" };
        private string tableName = "HF_WorkTaskInstance";
        private string keyField = "WorkTaskInstanceId";
        private string sqlString = "";

        #endregion

        #region  私有方法
        private void setParameter(WorkTaskInstanceEntity entity)
        {
            sqlDataItem.ParameterList.Clear();
            sqlDataItem.AppendParameter("@WorkTaskInstanceId", entity.WorkTaskInstanceId, typeof(string));
            sqlDataItem.AppendParameter("@WorkFlowId", entity.WorkFlowId, typeof(string));
            sqlDataItem.AppendParameter("@WorkTaskId", entity.WorkTaskId, typeof(string));
            sqlDataItem.AppendParameter("@WorkFlowInstanceId", entity.WorkFlowInstanceId, typeof(string));
            sqlDataItem.AppendParameter("@PreviousTaskInstanceId", entity.PreviousTaskInstanceId, typeof(string));
            sqlDataItem.AppendParameter("@TaskInstanceCaption", entity.TaskInstanceCaption, typeof(string));
            sqlDataItem.AppendParameter("@StartTime", entity.StartTime, typeof(DateTime));
            sqlDataItem.AppendParameter("@EndTime", entity.EndTime, typeof(DateTime));
            sqlDataItem.AppendParameter("@Status", entity.Status, typeof(string));
            sqlDataItem.AppendParameter("@OperatedDes", entity.OperatedDes, typeof(string));
            sqlDataItem.AppendParameter("@OperatorInstanceId", entity.OperatorInstanceId, typeof(string));
            sqlDataItem.AppendParameter("@SuccessMsg", entity.SuccessMsg, typeof(string));
            sqlDataItem.AppendParameter("@OutTimeed", entity.OutTimeed, typeof(bool));
            sqlDataItem.AppendParameter("@Reminded", entity.Reminded, typeof(bool));
            sqlDataItem.AppendParameter("@Description", entity.Description, typeof(string));
        }

        private void setInsertSql()
        {
            string tmpValueList = "";
            string tmpFieldName = "";
            sqlString = "insert into " + tableName + "(";
            int tmpInt = this.fieldList.Length;
            for (int i = 0; i < tmpInt - 1; i++)
            {
                tmpFieldName = fieldList[i].ToString();
                sqlString = sqlString + tmpFieldName + ", ";
                tmpValueList = tmpValueList + "@" + tmpFieldName + ",";
            }
            tmpFieldName = this.fieldList[tmpInt - 1].ToString();
            sqlString = sqlString + tmpFieldName;
            tmpValueList = tmpValueList + "@" + tmpFieldName;
            this.sqlString = sqlString + ")values(" + tmpValueList + ")";
            sqlDataItem.CommandText = sqlString;
        }

        private void setUpdateSql()
        {
            string tmpFieldName = "";
            int tmpInt = this.fieldList.Length;
            sqlString = "update " + tableName + " set ";
            for (int i = 0; i < tmpInt - 1; i++)
            {
                tmpFieldName = fieldList[i].ToString();
                sqlString = sqlString + tmpFieldName + " = @" + tmpFieldName + ", ";
            }
            tmpFieldName = this.fieldList[tmpInt - 1].ToString();
            sqlString = sqlString + tmpFieldName + " = @" + tmpFieldName;
            sqlString = sqlString + " where " + keyField + "=@" + this.keyField;
            sqlDataItem.CommandText = sqlString;
        }

        public WorkTaskInstanceEntity GetWorkTaskInstanceEntity(DataRow dr)
        {
            WorkTaskInstanceEntity entity = new WorkTaskInstanceEntity();
            string value = "";
            entity.WorkTaskInstanceId = dr["WorkTaskInstanceId"].ToString();
            entity.WorkFlowId = dr["WorkFlowId"].ToString();
            entity.WorkTaskId = dr["WorkTaskId"].ToString();
            entity.WorkFlowInstanceId = dr["WorkFlowInstanceId"].ToString();
            entity.PreviousTaskInstanceId = dr["PreviousTaskInstanceId"].ToString();
            entity.TaskInstanceCaption = dr["TaskInstanceCaption"].ToString();
            value = dr["StartTime"].ToString();
            if (string.IsNullOrEmpty(value) == false)
            {
                entity.StartTime = Convert.ToDateTime(value);
            }
            value = dr["EndTime"].ToString();
            if (string.IsNullOrEmpty(value) == false)
            {
                entity.EndTime = Convert.ToDateTime(value);
            }
            entity.Status = dr["Status"].ToString();
            entity.OperatedDes = dr["OperatedDes"].ToString();
            entity.OperatorInstanceId = dr["OperatorInstanceId"].ToString();
            entity.SuccessMsg = dr["SuccessMsg"].ToString();
            value = dr["OutTimeed"].ToString();
            if (string.IsNullOrEmpty(value) == false)
            {
                if ((value == "1") || (value.ToLower() == "true"))
                {
                    entity.OutTimeed = true;
                }
                else
                {
                    entity.OutTimeed = false;
                }
            }
            value = dr["Reminded"].ToString();
            if (string.IsNullOrEmpty(value) == false)
            {
                if ((value == "1") || (value.ToLower() == "true"))
                {
                    entity.Reminded = true;
                }
                else
                {
                    entity.Reminded = false;
                }
            }
            entity.Description = dr["Description"].ToString();
            return entity;
        }

        #endregion

        #region  构造函数
        public WorkTaskInstance()
        { }
        public static WorkTaskInstance GetInstance()
        {
            return new WorkTaskInstance();
        }
        #endregion

        #region  公有方法
        #region  基本方法
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="entity">数据实体</param>
        /// <returns>影响的记录条数</returns>
        public int Insert(WorkTaskInstanceEntity entity)
        {
            try
            {
                setInsertSql();//设定insert语句
                setParameter(entity);//设定参数
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteNonQuery(sqlDataItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity">数据实体</param>
        /// <returns>影响的记录条数</returns>
        public int Update(WorkTaskInstanceEntity entity)
        {
            try
            {
                setUpdateSql();//设定insert语句
                setParameter(entity);//设定参数
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteNonQuery(sqlDataItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string workTaskInstanceId)
        {
            string tmpSql = "select * from " + tableName + " where " + keyField + "=@" + keyField;
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = tmpSql;
            sqlItem.AppendParameter("@" + keyField, workTaskInstanceId);
            ClientDBAgent agent = new ClientDBAgent();
            return agent.RecordExists(sqlItem);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="workTaskInstanceId">主键Id</param>
        /// <returns>影响的记录条数</returns>
        public void Delete(string workTaskInstanceId)
        {
            try
            {
                string tmpSql = "delete from " + tableName + " where  " + keyField + "=@" + keyField;
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@" + keyField, workTaskInstanceId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取一条数据记录
        /// </summary>
        /// <param name="WorkTaskInstanceId">主键Id</param>
        /// <returns>DataTable</returns>
        public DataTable GetWorkTaskInstanceTable(string workTaskInstanceId)
        {
            string tmpSql = "select * from " + tableName + " where " + keyField + "=@" + keyField;
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@" + keyField, workTaskInstanceId);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取一个数据实体
        /// </summary>
        /// <param name="workTaskInstanceId">主键Id</param>
        /// <returns>DataTable</returns>
        public WorkTaskInstanceEntity GetWorkTaskInstanceEntity(string workTaskInstanceId)
        {
            DataTable dt = GetWorkTaskInstanceTable(workTaskInstanceId);
            if (dt != null && dt.Rows.Count > 0)
            {
                return GetWorkTaskInstanceEntity(dt.Rows[0]);
            }
            return null;
        }

        #endregion

        #region  扩展方法
        //此处添加扩展方法
        /// <summary>
        /// 某一任务实际处理者
        /// </summary>
        /// <param name="workFlowInstanceId">流程实例Id</param>
        /// <param name="workTaskId">任务节点Id</param>
        /// <returns>DataTable</returns>
        public  DataTable GetTaskInstanceUser(string workFlowInstanceId, string workTaskId)
        {
            string sql = @"select * from HF_WorkTaskInstanceView
                          where WorkFlowInstanceId=@WorkFlowInstanceId and WorkTaskId=@WorkTaskId and status=@status";
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = sql;
            sqlItem.AppendParameter("@WorkFlowInstanceId", workFlowInstanceId);
            sqlItem.AppendParameter("@WorkTaskId", workTaskId);
            sqlItem.AppendParameter("@status", WorkFlowConst.TaskStatus_3);//必须是已完成的任务
            ClientDBAgent agent = new ClientDBAgent();
            return agent.ExecuteDataTable(sqlItem);
        }
        /// <summary>
        /// 某一任务实际处理者
        /// </summary>
        /// <param name="workFlowInstanceId">流程实例Id</param>
        /// <param name="workTaskId">任务节点Id</param>
        /// <returns>Entitys</returns>
        public List<UserEntity>  GetTaskInstanceUserEntitys(string workFlowInstanceId, string workTaskId)
        {
            List<UserEntity> result = new List<UserEntity>();
            DataTable dt = GetTaskInstanceUser(workFlowInstanceId, workTaskId);
            UserData userData = new UserData();
            foreach (DataRow dr in dt.Rows)
            {
                UserEntity entity = userData.GetUserEntity(dr);
                result.Add(entity);
            }
            return result;

        }
        /// <summary>
        /// 获得动态配置的下一任务处理人
        /// </summary>
        /// <param name="workFlowId">流程模板Id</param>
        /// <param name="workTaskId">任务模板Id</param>
        /// <param name="workFlowInstanceId">流程实例Id</param>
        /// <param name="workTaskInstanceId">任务实例Id</param>
        /// <returns>DataTable</returns>
        public  DataTable GetTaskInsNextOper(string workFlowId, string workTaskId, string workFlowInstanceId, string workTaskInstanceId)
        {
            try
            {
                string sql = "select * from HF_WorkTaskInstanceNextOper where workFlowId=@workFlowId and workTaskId=@workTaskId " +
                             " and workFlowInstanceId=@workFlowInstanceId and workTaskInstanceId=@workTaskInstanceId";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sql;
                sqlItem.AppendParameter("@workFlowId", workFlowId);
                sqlItem.AppendParameter("@workTaskId", workTaskId);
                sqlItem.AppendParameter("@workFlowInstanceId", workFlowInstanceId);
                sqlItem.AppendParameter("@workTaskInstanceId", workTaskInstanceId);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获得动态配置的下一任务处理人
        /// </summary>
        /// <param name="workFlowId">流程模板Id</param>
        /// <param name="workTaskId">任务模板Id</param>
        /// <param name="workFlowInstanceId">流程实例Id</param>
        /// <param name="workTaskInstanceId">任务实例Id</param>
        /// <returns>Entitys</returns>
        public List<WorkTaskInstanceNextOperEntity> GetTaskInsNextOperEntitys(string workFlowId, string workTaskId, string workFlowInstanceId, string workTaskInstanceId)
        {
            try
            {
                List<WorkTaskInstanceNextOperEntity> result = new List<WorkTaskInstanceNextOperEntity>();
                DataTable dt = GetTaskInsNextOper(workFlowId, workTaskId, workFlowInstanceId, workTaskInstanceId);
                foreach (DataRow dr in dt.Rows)
                {
                    WorkTaskInstanceNextOperEntity entity =new WorkTaskInstanceNextOperEntity();
                    entity.WorkFlowId = dr["WorkFlowId"].ToString();
                    entity.WorkTaskId = dr["WorkTaskId"].ToString();
                    entity.WorkFlowInstanceId = dr["WorkFlowInstanceId"].ToString();
                    entity.WorkTaskInstanceId = dr["WorkTaskInstanceId"].ToString();
                    entity.UserId = dr["UserId"].ToString();
                    entity.UserName = dr["UserName"].ToString();
                    entity.NextOperId = dr["NextOperId"].ToString();
                    entity.Status = dr["Status"].ToString();
                    result.Add(entity);
                }
                return result;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 设定任务实例正常结束
        /// </summary>
        public static void SetWorkTaskInstanceOver(string operatedDes, string workTaskInstanceId)
        {
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = "HF_SetWorkTaskInstanceOverPro";
                sqlItem.CommandType = CommandType.StoredProcedure.ToString();
                sqlItem.AppendParameter("@operatedDes", operatedDes);
                sqlItem.AppendParameter("@WorktaskInsId", workTaskInstanceId);
                ClientDBAgent agent = new ClientDBAgent();
                int i=  agent.ExecuteNonQuery(sqlItem);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 设定任务实例成功提交信息
        /// </summary>
        public static void SetSuccessMsg(string successMsg, string workTaskInstanceId)
        {
            string sql = "update HF_WorkTaskInstance set SuccessMsg=@successMsg where WorkTaskInstanceId=@WorkTaskInstanceId";
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sql;
                sqlItem.AppendParameter("@successMsg", successMsg);
                sqlItem.AppendParameter("@WorkTaskInstanceId", workTaskInstanceId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 设置任务到达提醒关闭
        /// </summary>
        /// <param name="workTaskInstanceId">任务实例Id</param>
        public static void SetTaskRemindClose(string workTaskInstanceId)
        {
            string sql = " update HF_WorkTaskInstance set Reminded='1' where WorkTaskInstanceId=@WorkTaskInstanceId";
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sql;
                sqlItem.AppendParameter("@WorkTaskInstanceId", workTaskInstanceId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 设置任务超时提醒关闭
        /// </summary>
        /// <param name="workTaskInstanceId">任务实例Id</param>
        public static void SetTaskOutTimeClose(string workTaskInstanceId)
        {
            string sql = " update HF_WorkTaskInstance set OutTimeed='1' where WorkTaskInstanceId=@WorkTaskInstanceId";
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sql;
                sqlItem.AppendParameter("@WorkTaskInstanceId", workTaskInstanceId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 认领任务
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="worktaskInsId">任务实例Id</param>
        public static string WorkTaskClaim(string userId, string operatorInsId)
        {
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = "HF_WorkTaskClaimPro";
                sqlItem.CommandType = CommandType.StoredProcedure.ToString();
                sqlItem.AppendParameter("@OperatorInstanceId", operatorInsId);
                sqlItem.AppendParameter("@UserId", userId);
                ClientDBAgent agent = new ClientDBAgent();
                int i = agent.ExecuteNonQuery(sqlItem);
                if (i > 0)
                {
                    return WorkFlowConst.SuccessCode;
                }
                else
                {
                    return WorkFlowConst.TaskClaimErrorCode;
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 放弃认领任务
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="operatorInsId">处理者实例Id</param>
        public static string WorkTaskUnClaim(string userId, string operatorInsId)
        {
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = "HF_WorkTaskUnClaimPro";
                sqlItem.CommandType = CommandType.StoredProcedure.ToString();
                sqlItem.AppendParameter("@OperatorInstanceId", operatorInsId);
                sqlItem.AppendParameter("@UserId", userId);
                ClientDBAgent agent = new ClientDBAgent();
                int i = agent.ExecuteNonQuery(sqlItem);
                if (i > 0)
                {
                    return WorkFlowConst.SuccessCode;
                }
                else
                {
                    return WorkFlowConst.TaskUnClaimErrorCode;
                }


            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 指派任务
        /// </summary>
        /// <param name="userId">当前用户Id</param>
        /// <param name="assignUserId">指派人Id</param>
        /// <param name="operatorInsId">处理者实例Id</param>
        /// <returns></returns>
        public static string WorkTaskAssign(string userId, string assignUserId,string operatorInsId)
        {
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = "HF_WorkTaskAssignPro";
                sqlItem.CommandType = CommandType.StoredProcedure.ToString();
                sqlItem.AppendParameter("@AssignUserId", assignUserId);
                //sqlItem.AppendParameter("@WorkTaskInstanceId",)
                sqlItem.AppendParameter("@operatorInsId", operatorInsId);
                sqlItem.AppendParameter("@UserId", userId);
                ClientDBAgent agent = new ClientDBAgent();
                int i = agent.ExecuteNonQuery(sqlItem);
                if (i > 0)
                {
                    return WorkFlowConst.SuccessCode;
                }
                else
                {
                    return WorkFlowConst.TaskAssignErrorCode;
                }


            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 退回任务
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="operatorInsId">处理者实例Id</param>
        /// <returns>操作码</returns>
        public static string WorkTaskBack(string userId, string operatorInsId)
        {
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = "HF_WorkTaskBackPro";
                sqlItem.CommandType = CommandType.StoredProcedure.ToString();
                sqlItem.AppendParameter("@OperatorInstanceId", operatorInsId);
                sqlItem.AppendParameter("@UserId", userId);
                ClientDBAgent agent = new ClientDBAgent();
                int i = agent.ExecuteNonQuery(sqlItem);
                if (i > 0)
                {
                    return WorkFlowConst.SuccessCode;
                }
                else
                {
                    return WorkFlowConst.TaskAssignErrorCode;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 退回任务至申请人
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="operatorInsId">处理者实例Id</param>
        /// <returns>操作码</returns>
        public static string WorkTaskBackApplicant(string userId, string operatorInsId)
        {
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = "HF_WorkTaskBackProApplicant";
                sqlItem.CommandType = CommandType.StoredProcedure.ToString();
                sqlItem.AppendParameter("@OperatorInstanceId", operatorInsId);
                sqlItem.AppendParameter("@UserId", userId);
                ClientDBAgent agent = new ClientDBAgent();
                int i = agent.ExecuteNonQuery(sqlItem);
                if (i > 0)
                {
                    return WorkFlowConst.SuccessCode;
                }
                else
                {
                    return WorkFlowConst.TaskAssignErrorCode;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获得任务与流程实例视图
        /// </summary>
        /// <param name="workFlowInstanceId">流程实例Id</param>
        /// <returns>DataTable</returns>
        public DataTable GetWorkTaskInstanceView(string workTaskInstanceId)
        {
            string sql = @"select * from HF_WorkTaskInstanceView
                          where WorkTaskInstanceId=@WorkTaskInstanceId ";
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = sql;
            sqlItem.AppendParameter("@WorkTaskInstanceId", workTaskInstanceId);

            ClientDBAgent agent = new ClientDBAgent();
            return agent.ExecuteDataTable(sqlItem);
        }

        /// <summary>
        /// 获取下一节表单号
        /// </summary>
        /// <param name="PreviousTaskInstanceIde">当然任务实例ID</param>
        /// <param name="workTaskId">任务模板Id</param>
        /// <returns></returns>
        public DataTable GetNetTaskFormID(string PreviousTaskInstanceIde,string workTaskId)
        {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = "sp_HF_WorkTask_GetNetTaskFormID";
                sqlItem.CommandType = CommandType.StoredProcedure.ToString();
                sqlItem.AppendParameter("@PreviousTaskInstanceIde", PreviousTaskInstanceIde);
                sqlItem.AppendParameter("@workTaskId", workTaskId);
                ClientDBAgent agent = new ClientDBAgent();
               return agent.ExecuteDataTable(sqlItem);
        }

        /// <summary>
        /// 判断任务节点是否正在执行
        /// </summary>
        /// <param name="workFlowInstanceId">流程实例Id</param>
        /// <param name="workTaskId">任务模板Id</param>
        /// <returns></returns>
        public bool IsCurrentTask(string workFlowInstanceId, string workTaskId)
        {
            string sql = @"select * from HF_WorkTaskInstanceView
                          where WorkFlowInstanceId=@WorkFlowInstanceId  and workTaskId=@workTaskId and Status=@Status";
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = sql;
            sqlItem.AppendParameter("@WorkFlowInstanceId", workFlowInstanceId);
            sqlItem.AppendParameter("@workTaskId", workTaskId);
            sqlItem.AppendParameter("@Status", WorkFlowConst.TaskStatus_2);
            ClientDBAgent agent = new ClientDBAgent();
            return agent.RecordExists(sqlItem);
        }
        /// <summary>
        /// 判断当前任务节点的实例在流程实例中是否已经产生。
        /// 主要是针对控制节点实例的判断。
        /// </summary>
        /// <param name="workTaskId">当前任务节点Id</param>
        /// <param name="pWorkTaskInstance">前一任务实例Id</param>
        /// <returns>如果存在返回任务实例的Id</returns>
        public string GetExistsTaskInstance(string workTaskId, string pWorkTaskInstanceId)
        {
            string sql = @"select workTaskInstanceId from HF_WorkTaskInstance where PreviousTaskInstanceId=@pTaskInstance and workTaskId=@workTaskId";
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = sql;
            sqlItem.AppendParameter("@pTaskInstance", pWorkTaskInstanceId);
            sqlItem.AppendParameter("@workTaskId", workTaskId);
            sqlItem.AppendParameter("@Status", WorkFlowConst.TaskStatus_2);//不需要认领任务的节点，直接引入执行。
            ClientDBAgent agent = new ClientDBAgent();
            return agent.ExecuteScalar(sqlItem);
        }
        /// <summary>
        /// 获取任务处理信息
        /// </summary>
        /// <param name="workTaskId">任务模板Id</param>
        /// <param name="workFlowInstanceId">任务实例Id</param>
        /// <returns>提交返回信息</returns>
        public static string GetTaskDoneWhoMsg(string workTaskId, string workFlowInstanceId)
        {
            try
            {
                string result = "";
                string sql = "select distinct workflowInstanceId,worktaskid,operateddes,taskendtime,OperContentText,OperType,OperStatus from HF_WorkTaskInstanceView  where WorkTaskId= @worktaskId " +
                             " and status=3 and workflowInstanceId=@workflowInsId and OperType !='12' and UserId !='' " +
                             " and taskEndTime >= (select min(taskEndTime) from HF_WorkTaskInstanceView where workflowInstanceId=@workflowInsId " +
                             " and TaskTypeId = '1') order by taskendtime,OperType";
                
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sql;
                sqlItem.AppendParameter("@workTaskId", workTaskId);
                sqlItem.AppendParameter("@workFlowInsId", workFlowInstanceId);
                ClientDBAgent agent = new ClientDBAgent();
                DataTable dt = agent.ExecuteDataTable(sqlItem);
                List<string> str = new List<string>();
                if (dt != null & dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count - 1; i++)
                    {
                        string operdes = string.Empty;
                        if (dt.Rows[i]["operateddes"].ToString() != "" && dt.Rows[i]["OperContentText"].ToString() != "" && dt.Rows[i]["OperType"].ToString() != "7"  && dt.Rows[i]["OperStatus"].ToString() != "2")
                        {
                            string opderated = string.Empty;
                            if (dt.Rows[i]["operateddes"].ToString().Split('→').Length == 1)
                            {
                                opderated = dt.Rows[i]["operateddes"].ToString().Split('→')[0].ToString();
                            }
                            else 
                            {
                                opderated = dt.Rows[i]["operateddes"].ToString().Split('→')[1].ToString();
                            }
                            if (opderated != dt.Rows[i]["OperContentText"].ToString())
                            {
                               operdes = dt.Rows[i]["OperContentText"].ToString() + "->" + dt.Rows[i]["operateddes"].ToString().Split(',')[0].ToString();
                               
                            }
                            else
                            {
                                operdes = dt.Rows[i]["OperContentText"].ToString();
                            }
                        }
                        else
                        {
                            operdes = dt.Rows[i]["OperContentText"].ToString();
                        }
                      
                        if (result != "")
                        {
                            if (!str.Contains(operdes))
                            {
                                str.Add(operdes);
                                result += "|" + operdes;
                            }
                           
                        }
                        else 
                        {
                            str.Add(operdes);
                            result = operdes;
                        }
                    }
                    string operds = string.Empty;
                    if (dt.Rows[dt.Rows.Count - 1]["operateddes"].ToString() != "" && dt.Rows[dt.Rows.Count - 1]["OperContentText"].ToString() != "" && dt.Rows[dt.Rows.Count - 1]["OperStatus"].ToString() != "2" && dt.Rows[dt.Rows.Count - 1]["OperType"].ToString() != "7" )
                    {
                        if (dt.Rows[dt.Rows.Count - 1]["operateddes"].ToString().Split('→')[0].ToString() != dt.Rows[dt.Rows.Count - 1]["OperContentText"].ToString())
                        {
                            if (!str.Contains(dt.Rows[dt.Rows.Count - 1]["OperContentText"].ToString()))
                            {
                                str.Add(dt.Rows[dt.Rows.Count - 1]["OperContentText"].ToString());
                                if (result != "")
                                {
                                    result += "|" + dt.Rows[dt.Rows.Count - 1]["OperContentText"].ToString() + "->" + dt.Rows[dt.Rows.Count - 1]["operateddes"].ToString().Split(',')[0].ToString();
                                }
                                else
                                {
                                    result = dt.Rows[dt.Rows.Count - 1]["OperContentText"].ToString() + "->" + dt.Rows[dt.Rows.Count - 1]["operateddes"].ToString().Split(',')[0].ToString();
                                }
                               
                            }
                            else 
                            {
                                result += "->" + dt.Rows[dt.Rows.Count - 1]["operateddes"].ToString().Split(',')[0].ToString();
                            }
                        }
                        else
                        {
                            if (!str.Contains(dt.Rows[dt.Rows.Count - 1]["OperContentText"].ToString()))
                            {
                                str.Add(dt.Rows[dt.Rows.Count - 1]["OperContentText"].ToString());
                                if (result != "")
                                {
                                    result = result + "|" + dt.Rows[dt.Rows.Count - 1]["OperContentText"].ToString();
                                }
                                else
                                {
                                    result = dt.Rows[dt.Rows.Count - 1]["OperContentText"].ToString();
                                }
                               
                            }
                        }
                    }
                    else
                    {
                        if (!str.Contains(dt.Rows[dt.Rows.Count - 1]["OperContentText"].ToString()))
                        {
                            str.Add(dt.Rows[dt.Rows.Count - 1]["OperContentText"].ToString());
                            result = result + "|"+dt.Rows[dt.Rows.Count - 1]["OperContentText"].ToString();
                        }
                      
                    }
                   
                }
                return result;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取当前审核任务信息
        /// </summary>
        /// <param name="workTaskId">任务模板Id</param>
        /// <param name="workFlowInstanceId">任务实例Id</param>
        /// <returns>提交返回信息</returns>
        public static string GetTaskOperDoneWhoMsg(string workTaskId, string workFlowInstanceId)
        {
            try
            {
                string result = "";
                string sql = "select distinct workflowInstanceId,worktaskid,operateddes,OperContentText,taskendtime,OperType from HF_WorkTaskInstanceView  where WorkTaskId= @worktaskId " +
               " and  (status=1 or status=2 or status = 5) and OperType !='12'  and OperContentText !='' and workflowInstanceId=@workflowInsId order by taskendtime,OperType";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sql;
                sqlItem.AppendParameter("@workTaskId", workTaskId);
                sqlItem.AppendParameter("@workFlowInsId", workFlowInstanceId);
                ClientDBAgent agent = new ClientDBAgent();
                DataTable dt = agent.ExecuteDataTable(sqlItem);

                //string sqls = "select distinct workflowInstanceId,worktaskid,operateddes,taskendtime,OperContentText from HF_WorkTaskInstanceView  where WorkTaskId= @worktaskId " +
                //             " and (status=3) and workflowInstanceId=@workflowInsId " +
                //             " and taskEndTime >= (select min(taskEndTime) from HF_WorkTaskInstanceView where workflowInstanceId=@workflowInsId " +
                //             " and TaskTypeId = '1') order by taskendtime";
                //SqlDataItem sqlItems = new SqlDataItem();
                //sqlItems.CommandText = sqls;
                //sqlItems.AppendParameter("@workTaskId", workTaskId);
                //sqlItems.AppendParameter("@workFlowInsId", workFlowInstanceId);
                //ClientDBAgent agents = new ClientDBAgent();
                //DataTable dst = agent.ExecuteDataTable(sqlItems);

                //if (dst != null & dst.Rows.Count > 0)
                //{
                //    for (int i = 0; i < dst.Rows.Count - 1; i++)
                //    {
                //        result = result + dst.Rows[i]["OperContentText"].ToString() + "|";
                //    }
                //    result = result + dst.Rows[dst.Rows.Count - 1]["OperContentText"].ToString();
                //}
                if (dt != null & dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count - 1; i++)
                    {
                        if (result != "")
                        {
                            result += "|";
                        }
                        result = result + dt.Rows[i]["OperContentText"].ToString();

                    }
                    if (result != "")
                    {
                        result += "|";
                    }
                    result = result + dt.Rows[dt.Rows.Count - 1]["OperContentText"].ToString();
                }
                return result;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获得任务提交给谁了
        /// </summary>
        ///  <param name="workTaskInstanceId">任务实例Id</param>
        ///  <returns>返回信息</returns>
        public static string GetTaskToWhoMsg(string workTaskInstanceId)
        {
            try
            {
                DataTable dt = null;
                int inum = 0;
                string result = ""; int taskType; string operContentText = "";
                for (int i = 0; inum <= 0; i++)
                {

                    string sql = "select * from HF_WorkTaskInstanceView  where PreviousTaskInstanceId= @worktaskInsId " +
                                  " and (operstatus='0' or operstatus is null) order by opertype";
                    SqlDataItem sqlItem = new SqlDataItem();
                    sqlItem.CommandText = sql;
                    sqlItem.AppendParameter("@worktaskInsId", workTaskInstanceId);
                    ClientDBAgent agent = new ClientDBAgent();
                    dt = agent.ExecuteDataTable(sqlItem);
                    if (dt.Rows.Count > 0)
                    {
                        inum = 1;
                    }
                    if (dt.Rows.Count == 0)
                    {
                        string sqlto = "select WorkTaskInstanceId from HF_WorkTaskInstanceView where PreviousTaskInstanceId='" + workTaskInstanceId + "'";
                        sqlItem.CommandText = sqlto;
                        string worktaskinsid = agent.ExecuteScalar(sqlItem);
                        if (worktaskinsid != "")
                        {
                            workTaskInstanceId = worktaskinsid;
                        }
                        else
                        {
                            inum = 1;
                        }
                    }
                }
                if (dt != null & dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count ; i++)
                    {
                        if (dt.Rows[i]["OperType"].ToString() != "12")
                        {
                            taskType = Convert.ToInt16(dt.Rows[i]["tasktypeid"].ToString());
                            switch (taskType)
                            {
                                case WorkFlowConst.TaskType_SubWorkFlow:
                                    operContentText = "进入子流程" + ",";
                                    break;
                                case WorkFlowConst.TaskType_End:
                                    operContentText = "流程正常结束" + ",";
                                    break;
                                case WorkFlowConst.TaskType_Judge:
                                    operContentText = "控制节点" + ",";
                                    break;
                                default:
                                    operContentText = dt.Rows[i]["operContentText"].ToString() + ",";
                                    break;
                            }

                            result = result + operContentText;
                        }
                    }
                    //result = result.TrimEnd(',');
                    if (string.IsNullOrEmpty(result))
                    {
                        result = GetResultInfo(dt);
                    }
                    //result = result + dt.Rows[dt.Rows.Count - 1]["operContentText"].ToString();
                }
                if (string.IsNullOrEmpty(result))
                {
                    string sqles = "select * from HF_WorkTaskInstanceView where WorkFlowNo = (select distinct WorkFlowNo  from HF_WorkTaskInstanceView where WorkTaskInstanceId = @worktaskInsIds) "+ 
                                  " and TaskTypeId = '1' and Status = '4'";
                    SqlDataItem sqlItemes = new SqlDataItem();
                    sqlItemes.CommandText = sqles;
                    sqlItemes.AppendParameter("@worktaskInsIds", workTaskInstanceId);
                    ClientDBAgent agent = new ClientDBAgent();
                    DataTable dts = agent.ExecuteDataTable(sqlItemes);
                    if (dts.Rows.Count <=0)
                       ErrorLogData.WriteLog("HF.WorkFlow.Engine.DLL", "WorkTaskInstance.cs", "GetTaskToWhoMsg("+workTaskInstanceId+")", "", WorkFlowConst.TaskToWhoMsgLogs, WorkFlowConst.TaskToWhoMsgLogs, "1", "1", workTaskInstanceId);
                }
                return result;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static string GetResultInfo(DataTable dt)
        {
            int taskTypes;
            string operContentText = "";
            string result = "";
            if (dt != null & dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    taskTypes = Convert.ToInt16(dt.Rows[i]["tasktypeid"].ToString());
                    switch (taskTypes)
                    {
                        case WorkFlowConst.TaskType_SubWorkFlow:
                            operContentText = "进入子流程" + ",";
                            break;
                        case WorkFlowConst.TaskType_End:
                            operContentText = "流程正常结束" + ",";
                            break;
                        case WorkFlowConst.TaskType_Judge:
                            operContentText = "控制节点" + ",";
                            break;
                        default:
                            operContentText = dt.Rows[i]["operContentText"].ToString() + ",";
                            break;
                    }

                    result = result + operContentText;
                }
                result = result.TrimEnd(',');
                //result = result + dt.Rows[dt.Rows.Count - 1]["operContentText"].ToString();
            }
            return result;
        }
        /// <summary>
        /// 获得任务成功提交信息
        /// </summary>
        /// <param name="workTaskInstanceId">任务实例Id</param>
        /// <returns>返回信息</returns>
        public static string GetResultMsg(string workTaskInstanceId)
        {
            try
            {
                string sql = "select SuccessMsg from HF_WorkTaskInstance  where workTaskInstanceId= @workTaskInstanceId ";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sql;
                sqlItem.AppendParameter("@workTaskInstanceId", workTaskInstanceId);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteScalar(sqlItem);


            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获得一个任务模板在流程实例中的所有任务实例
        /// </summary>
        /// <param name="worktaskId">任务模板Id</param>
        /// <returns></returns>
        public  DataTable GetTaskInstance( string workFlowInstanceId, string workTaskId)
        {
            try
            {
               string sqlStrs = "select * from HF_WorkTaskInstanceView where " +
             "  workFlowInstanceId=@workflowInsId and TaskTypeId = '1' and Status = '4'";
                SqlDataItem sqlItems = new SqlDataItem();
                sqlItems.CommandText = sqlStrs;
                sqlItems.AppendParameter("@workflowInsId", workFlowInstanceId);
                sqlItems.AppendParameter("@worktaskid", workTaskId);
                ClientDBAgent agents = new ClientDBAgent();
                DataTable dt = agents.ExecuteDataTable(sqlItems);

                if (dt.Rows.Count > 0)
                {
                    return null;
                }
                else
                {
                    string sqlStr = "select * from HF_WorkTaskInstanceView where " +
                        "  workFlowInstanceId=@workflowInsId and worktaskid=@worktaskid "+
                        "  and taskStartTime >= (select min(taskStartTime) from HF_WorkTaskInstanceView where workflowInstanceId=@workflowInsId " +
                        "  and TaskTypeId = '1') and (OperType <> '12'or OperType is null)";
                    SqlDataItem sqlItem = new SqlDataItem();
                    sqlItem.CommandText = sqlStr;
                    sqlItem.AppendParameter("@workflowInsId", workFlowInstanceId);
                    sqlItem.AppendParameter("@worktaskid", workTaskId);
                    ClientDBAgent agent = new ClientDBAgent();
                    return agent.ExecuteDataTable(sqlItem);
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获得所有具备到达提醒条件的任务,依此进行任务提醒。
        /// </summary>
        /// <returns></returns>
        public DataTable GetRemindWorkTasks()
        {
            try
            {
                string sqlStr = " select * from HF_RemindWorkTasksView ";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sqlStr;
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获得所有具备超时提醒条件的任务，依此进行超时提醒。
        /// </summary>
        /// <returns></returns>
        public DataTable GetOutTimeWorkTasks()
        {
            try
            {
                string sqlStr = "select * from HF_OutTimeWorkTasksView ";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sqlStr;
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取任务实例节点的类型
        /// </summary>
        /// <param name="WorkTaskInstanceId">任务实例节点ID</param>
        /// <returns></returns>
        public static string GetWorkTaskTypeID(string WorkTaskInstanceId)
        {
            try
            {
                string sql = "	select TaskTypeId from HF_WorkTaskInstanceView where WorkTaskInstanceId = @WorkTaskInstanceId ";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sql;
                sqlItem.AppendParameter("@WorkTaskInstanceId", WorkTaskInstanceId);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteScalar(sqlItem);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void SetWorkTaskInsStatus(string workTaskInstanceId)
        {
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = "HF_SetWorkTaskStatus";
                sqlItem.CommandType = CommandType.StoredProcedure.ToString();
                sqlItem.AppendParameter("@WorkTaskInsId", workTaskInstanceId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        #endregion
    }
}

